﻿using ArmyCreator;
using DataModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Windows.Storage.Streams;

namespace WebCalls
{
    public class RetrieveListings
    {
        public async static Task Get(string login, string password)
        {
            Caller caller = new Caller();
            Dictionary<string, object> parameters = new Dictionary<string, object>();

            parameters.Add("login", login);
            parameters.Add("password", password);

            String result = await caller.Call(Urls.GET_LISTINGS, parameters);

            var user = SerializationUtils.Deserialize<DataModel.User>(result);

            if (user != null)
            {
                UserContext.Instance.Listings.Clear();
                foreach (var group in user.Groups)
                {
                    foreach (var army in group.Armies)
                    {
                        Listing listing = new Listing() { Army = army, Group = group, IsLoaded = false };
                        UserContext.Instance.Listings.Add(listing);

                        if (UserContext.Instance.LoadAllAtStartup)
                        {
                            RetrieveListing.Get(listing.Army.Id);
                        }
                    }
                }
            }
        }

    }
}
